//
//  NSDate+Extension.swift
//  sina_weibo
//
//  Created by 刘刘海强 on 16/5/16.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit

extension NSDate {
   
    //定义类方法，根据时间字符串创建一个时间对象
    class func createTimeWithString(time: String) -> NSDate {
        
        let dateFormatter = NSDateFormatter()
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        return dateFormatter.dateFromString(time)!
        
    }
    
    var sinaTime: String? {
        
        let dateFormatter = NSDateFormatter()
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        
        if isThisYear(self) {
            //是今年
            let calendar = NSCalendar.currentCalendar()
            if calendar.isDateInToday(self) {
                //是今天
                let interval = abs(self.timeIntervalSinceNow)
                if interval < 60 {
                    return "刚刚"
                } else if interval < 3600 {
                    let result = interval / 60
                    return "\(Int(result))分钟前"
                } else {
                    let result = interval / 3600
                    return "\(Int(result))小时前"
                }
            } else if calendar.isDateInYesterday(self) {
                //是昨天
                dateFormatter.dateFormat = "昨天 HH:mm"
            } else {
                dateFormatter.dateFormat = "MM-dd HH:mm"
            }
            
        } else {
            //不是今年
            dateFormatter.dateFormat = "yyyy-MM-dd"
            
        }
        
        return dateFormatter.stringFromDate(self)

        
    }
    
    
    //判断是否为今年
    private func isThisYear(createAtDate: NSDate) -> Bool {
        
        let currentDate = NSDate()
        let dateformatter = NSDateFormatter()
        dateformatter.locale = NSLocale(localeIdentifier: "en_US")
        
        dateformatter.dateFormat = "yyyy"
        
        let currentDateYear = dateformatter.stringFromDate(currentDate)
        let createAtDateYear = dateformatter.stringFromDate(createAtDate)
        
        return currentDateYear == createAtDateYear
    }
    
}
